﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using UniRlv.COL;
using UniRlv.Utility;
using UniRlv.Utility.Extend;

namespace UniRlv.UI.Main.BasicInfo
{
    public partial class FrmPackageInfo : UniRlv.UI.Main.FrmBase
    {
        List<ProductInfo> listProducts;
        BindingList<PackageRule> details = new BindingList<PackageRule>();
        ProductInfo curProduct = null;

        public FrmPackageInfo()
        {
            InitializeComponent();
        }

        private void FrmPackageInfo_Load(object sender, EventArgs e)
        {
            #region 初始化产品列表

            Wait();
            string msg = string.Empty;
            listProducts = DALOpr.QueryAll<ProductInfo>(ref msg);

            if (!string.IsNullOrEmpty(msg))
            {
                ShowErrorMessageBox("出现错误", msg);
            }
            else
            {
                if (listProducts == null || listProducts.Count == 0)
                {
                    ShowWarnningMessageBox("提示", "缺少产品信息");
                }
                else
                {
                    foreach (var item in listProducts)
                    {
                        lstProduct.Items.Add(item.ToString());
                    }

                    if (this.Tag != null)
                    {
                        curProduct = this.Tag as ProductInfo;
                        lstProduct.SelectedItem = curProduct.ToString();
                        lstProduct.Enabled = false;
                    }
                    else
                    {
                        lstProduct.SelectedIndex = 0;
                    }
                }

            }

            WaitBack();

            #endregion

            #region 初始化工具栏

            toolBtnModify.Visible = true;
            toolBtnAdd.Visible = true;
            toolBtnDelete.Visible = true;

            toolBtnAdd.Click += toolBtnAdd_Click;
            toolBtnDelete.Click += toolBtnDelete_Click;
            toolBtnModify.Click += toolBtnModify_Click;

            if (this.Tag != null)
            {
                ToolStripButton btnBackProduct = AddToolButton("productBack", "返回产品列表");
                btnBackProduct.Click += btnBackProduct_Click;
            }
            
            #endregion

            UIHelper.InitDataGridView(dgvDetails);
            dgvDetails.DataSource = details;
        }



        private void btnBackProduct_Click(object sender, EventArgs e)
        {
            FrmMain.GetInstance().SwitchFormByModuleName("ProductInfo", curProduct);
        }

        #region 工具栏事件响应

        private void toolBtnModify_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(curProduct.gg))
            {
                ShowWarnningMessageBox("提示", "当前产品缺少规格信息，请先完善产品信息");
                return;
            }

            if (dgvDetails.CurrentRow!=null && dgvDetails.CurrentRow.DataBoundItem != null)
            {
                PackageRule p = dgvDetails.CurrentRow.DataBoundItem as PackageRule;
               
                FrmAddOrEditPackage frm = new FrmAddOrEditPackage();
                frm.CurProduct = curProduct;
                frm.Tag = p;
                frm.Text = "修改包装信息";
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    p = frm.Tag as PackageRule;
                    string sql = EntityHelper.GetUpdateSql(p);
                    string msg = string.Empty;

                    if (DALOpr.ExecuteNonQuery(sql, ref msg))
                    {
                        int idx = details.IndexOf(p);
                        details.RemoveAt(idx);
                        details.Insert(idx, p);

                        dgvDetails.SetRowSelect(idx);

                        ShowInfoMessageBox("提示", "修改成功");
                    }
                    else
                    {
                        ShowErrorMessageBox("修改失败", msg);
                    }
                }
            }
            else
            {
                ShowInfoMessageBox("提示", "先选择需要修改的记录");
            }
        }

        private void toolBtnDelete_Click(object sender, EventArgs e)
        {
            if (dgvDetails.CurrentRow.DataBoundItem != null)
            {
                PackageRule p = dgvDetails.CurrentRow.DataBoundItem as PackageRule;

                if (ShowConfirmDialog("请确认", "确定要删除该记录？\r\n" + p.ToString()) == System.Windows.Forms.DialogResult.OK)
                {
                    string sql = "delete from PackageRule where id = " + p.ID;
                    string msg = string.Empty;

                    if (DALOpr.ExecuteNonQuery(sql, ref msg))
                    {
                        details.Remove(p);
                    }
                    else
                    {
                        ShowErrorMessageBox("删除失败", msg);
                    }
                }
            }
            else
            {
                ShowInfoMessageBox("提示", "先选择需要删除的记录");
            }
        }

        private void toolBtnAdd_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(curProduct.gg))
            {
                ShowWarnningMessageBox("提示", "当前产品缺少规格信息，请先完善产品信息");
                return;
            }

            FrmAddOrEditPackage frm = new FrmAddOrEditPackage();
            frm.CurProduct = curProduct;
            frm.Text = "添加包装信息";
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                PackageRule p = frm.Tag as PackageRule;
                string msg = string.Empty;

                if (details.Contains(p))
                {
                    ShowWarnningMessageBox("警告", "不允许添加同规格的包装信息");
                    return;
                }

                if (DALOpr.Insert(p, ref msg))
                {
                    details.Add(p);

                    dgvDetails.SetRowSelect(details.Count - 1);
                    ShowInfoMessageBox("提示", "添加成功");
                }
                else
                {
                    ShowErrorMessageBox("添加失败", msg);
                }
            }
        }

        #endregion

        private void lstProduct_SelectedIndexChanged(object sender, EventArgs e)
        {
            Wait();
            curProduct = null;
            foreach (var item in listProducts)
            {
                if (item.ToString().Equals(lstProduct.Text))
                {
                    curProduct = item;
                    break;
                }
            }

            if (curProduct == null)
            {
                ShowErrorMessageBox("出现错误", "无法查询到所选产品！");
                return;
            }

            string msg = string.Empty;

            List<PackageRule> rules = DALOpr.Query<PackageRule>("productID = " + curProduct.ID, ref msg);
            details.Clear();

            if (string.IsNullOrEmpty(msg))
            {
                if (rules!=null)
                {
                    foreach (var item in rules)
                    {
                        details.Add(item);
                    }
                }
            }
            else
            {
                ShowErrorMessageBox("出现错误", msg);
            }

            WaitBack();
        }

        private void dgvDetails_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvDetails.CurrentRow != null)
            {
                toolBtnModify.PerformClick();
            }
        }

        private void txtTym_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                toolBtnQuery.PerformClick();
            }
        }

        private void lstProduct_TextUpdate(object sender, EventArgs e)
        {
            //清空combobox
            lstProduct.Items.Clear();

            //遍历全部备查数据
            foreach (ProductInfo item in listProducts)
            {

                if (string.IsNullOrEmpty(lstProduct.Text))
                {//空，包含全部
                    lstProduct.Items.Add(item.ToString());
                }
                else
                {
                    if (item.ToString().Contains(lstProduct.Text))
                    {
                        //符合，插入ListNew
                        lstProduct.Items.Add(item.ToString());
                    }
                }
            }

            if (lstProduct.Items.Count == 0)
            {
                lstProduct.SelectionStart = lstProduct.Text.Length;
                return;
            }

            //设置光标位置，否则光标位置始终保持在第一列，造成输入关键词的倒序排列
            lstProduct.SelectionStart = lstProduct.Text.Length;
            //保持鼠标指针原来状态，有时候鼠标指针会被下拉框覆盖，所以要进行一次设置。
            Cursor = Cursors.Default;
            //自动弹出下拉框
            lstProduct.DroppedDown = true;
        }

        private void lstProduct_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (e.Index < 0)
            {
                return;
            }
            e.DrawBackground();
            e.DrawFocusRectangle();
            e.Graphics.DrawString(lstProduct.Items[e.Index].ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds.X, e.Bounds.Y + 3);
        }
    }
}
